package resources

import (
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/resources"
	"gitee.com/Luna-CY/hui-hui/server/http/response"
	"github.com/gin-gonic/gin"
	"strings"
)

type ListRequest struct {
	Path  string `json:"path" validate:"required" binding:"required"`                       // 路径
	Order int    `json:"order" validate:"optional" binding:"omitempty,oneof=1 2 3 4 5 6 7"` // 排序
}

type ListResponse struct {
	Data []ListEntry `json:"data" validate:"required"` // 列表
}

type ListEntry struct {
	Name       string `json:"name" validate:"required"`        // 名称
	IsDir      bool   `json:"is_dir" validate:"required"`      // 是否是目录
	Size       int64  `json:"size" validate:"required"`        // 文件大小
	UpdateTime int64  `json:"update_time" validate:"required"` // 更新时间
}

func (cls *Resources) List(c *gin.Context) (int, any, error) {
	var body = ListRequest{Order: int(resources.OrderDefault)}
	if err := c.ShouldBindJSON(&body); nil != err {
		return response.InvalidRequest, nil, err
	}

	entries, err := cls.resources.List(strings.Split(body.Path, "/"), resources.Order(body.Order))
	if nil != err {
		return response.Unknown, nil, err
	}

	var res = ListResponse{Data: make([]ListEntry, 0)}
	for _, entry := range entries {
		res.Data = append(res.Data, ListEntry{Name: entry.Name, IsDir: entry.IsDir, Size: entry.Size, UpdateTime: entry.UpdateTime})
	}

	return response.Ok, res, nil
}
